#include "camerathread.h"

CameraThread* CameraThread::camThread = nullptr;

CameraThread::CameraThread()
{
    this->sleep = 40;
    this->isRun = false;
    this->isStop = true;
}

CameraThread *CameraThread::getInstance()
{
    if(CameraThread::camThread == nullptr)
    {
        qDebug() << "first time create Instance" ;
        CameraThread::camThread = new CameraThread;
    }
    else
    {
        qDebug() << "2-n time";
    }
    return CameraThread::camThread;
}
//级联分类器人脸编制边框
void CameraThread::detecFaceRaw(cv::Mat &frame, cv::CascadeClassifier &cascade, double scale)
{
    //1.灰度处理
    cv::Mat gray;
    cv::cvtColor(frame, gray, CV_BGR2GRAY);
    //2.将灰度处理的结果图缩小到原来一半
    //opencv是先写高度，再写宽度
    cv::Mat smalling(cvRound(frame.rows/scale), cvRound(frame.cols/scale), CV_8UC1);
    cv::resize(gray, smalling, smalling.size(), 0, 0, cv::INTER_LINEAR);
    //3.直方图均衡化 利用直方图均衡化函数让图像黑白分明
    cv::equalizeHist(smalling, smalling);
    //4.用训练好级联分类器模型进行识别车辆
    std::vector<cv::Rect>faces;
    //扫描过程
    cascade.detectMultiScale(smalling, faces, 1.1 , 2,0|CV_HAAR_SCALE_IMAGE, cv::Size(30, 30));
    //5.绘制边框
    std::vector<cv::Rect>::const_iterator iter;
    for (iter = faces.begin(); iter!=faces.end(); iter++)
    {
        cv::rectangle(frame, cvPoint(cvRound(iter->x*scale), cvRound(iter->y*scale)),
                      cvPoint(cvRound((iter->x+iter->width)*scale),cvRound((iter->y+iter->height)*scale)),
                      cv::Scalar(0,255,0),
                      2,8);
    }
}

void CameraThread::videoInit()
{
    this->cap = new cv::VideoCapture(0);
    this->isStop = false;
    this->isRun = true;
}

bool CameraThread::getIsRun() const
{
    return isRun;
}

void CameraThread::setIsRun(bool value)
{
    isRun = value;
}

bool CameraThread::getIsStop() const
{
    return isStop;
}

void CameraThread::setIsStop(bool value)
{
    isStop = value;
}

void CameraThread::setSleep(unsigned long value)
{
    sleep = value;
}

void CameraThread::run()
{
    cv::CascadeClassifier cascade("../model/face.xml");
    while (!(this->isStop))
    {
        if(this->isRun)
        {
            this->cap->read(this->frame);
            this->detecFaceRaw(frame, cascade, 2);
            cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
            this->img = QImage(frame.data, frame.cols, frame.rows, frame.cols*frame.channels(), QImage::Format_RGB888);
            emit this->sendImg(this->img);
        }

    }
    this->terminate();
    this->cap->release();
}
